package tokenslb

import (
	"log"
	"strings"
	"sync"
)

const MaxUsedTime = 16

var Pool *KeyPool

type KeyPool struct {
	mu      sync.Mutex
	keys    map[string]*Counter
	keyMap  map[string]string
	lastIdx int
}

type Counter struct {
	uses int
}

func NewKeyPool(names string, tokens string) *KeyPool {
	nameArr := strings.Split(names, ",")
	tokenArr := strings.Split(tokens, ",")
	pool := &KeyPool{
		keys:   make(map[string]*Counter),
		keyMap: make(map[string]string),
	}
	for i, name := range nameArr {
		pool.keys[name] = &Counter{}
		pool.keyMap[name] = tokenArr[i]
	}
	Pool = pool
	return Pool
}

func GetKeyPool() *KeyPool {
	if Pool == nil {
		log.Fatal("keys not init")
		return nil
	}
	return Pool
}

func (kp *KeyPool) GetRandomKey() (name, token string) {
	kp.mu.Lock()
	defer kp.mu.Unlock()

	if len(kp.keys) == 0 {
		return "", ""
	}

	keys := make([]string, 0, len(kp.keys))
	for key := range kp.keys {
		keys = append(keys, key)
	}
	if kp.lastIdx > len(keys)-1 {
		kp.lastIdx = 0
	}
	i := kp.lastIdx
	kp.lastIdx++
	return keys[i], kp.keyMap[keys[i]]
}

func (kp *KeyPool) UseKey(key string) {
	kp.mu.Lock()
	counter := kp.keys[key]
	counter.uses++
	kp.mu.Unlock()
	/*	if counter.uses >= MaxUsedTime {
			delete(kp.keys, key)
		} else {
			kp.mu.Unlock()
		}*/

	/*time.AfterFunc(60*time.Second, func() {
		kp.ResetKey(key)
	})*/
}

func (kp *KeyPool) ResetKey(key string) {
	kp.mu.Lock()
	defer kp.mu.Unlock()

	if _, ok := kp.keys[key]; !ok {
		kp.keys[key] = &Counter{}
	} else {
		kp.keys[key].uses = 0
	}
}
